// if ('addEventListener' in document) {
// 	document.addEventListener('DOMContentLoaded', function() {
// 		FastClick.attach(document.body);
// 	}, false);
// }
var map = null
var nowPoint = null
var marker1 = null
var vue = new Vue({
    el: "#main",
    data() {
        return {
            tagList: [],
            number: "1",
            tempImages: [],
            ruleForm: {},
            msg: '',
            loading: false,
            placeList: [],
            prompt: false,
            addNote: false,
            id: '',
            detail: {},
            location: '',
            temp: {
                place_id: '',
                remark: '',
                images: []
            },
            noteList: [],
            userInfo: userInfo,
            rules: {
                contacts: [{
                    required: true,
                    message: '请输入联系人信息',
                    trigger: 'blur'
                }],
                category_id: [{
                    required: true,
                    message: '请选择场所分类',
                    trigger: 'blur'
                }],
                place_name: [{
                    required: true,
                    message: '请输入场所名称',
                    trigger: 'blur'
                }, ],
                content: [{
                    required: true,
                    message: '请输入情况说明',
                    trigger: 'change'
                }],
                address: [{
                    required: true,
                    message: '请输入场所信息',
                    trigger: 'change'
                }],
                is_small_place: [{
                    required: true,
                    message: '请选择是否为九小场所',
                    trigger: 'blur'
                }],
                is_cater: [{
                    required: true,
                    message: '请选择是否涉餐饮',
                    trigger: 'blur'
                }],
                first_tags: [{
                    required: true,
                    message: '请选择是否涉餐饮',
                    trigger: 'blur'
                }],
                grids_id: [{
                    required: true,
                    message: '请选择网格',
                    trigger: 'blur'
                }],
            },
            newRrmark: '',
            imagesList: [],
            idList: [],
            isManual: false,
            locationList: [],
            tempObj: {},
            isUploadImg: true,
            imgNumber: null,
            noteImgNumber: null,
            isUploadNoteImg: true,
            isUploadLoading: false,
            time: null,
            additionalObj: {},
            additionalList: [],
            communityInformation: [],
            serverDefaultValue: '',
            serverKey: 0
        }
    },
    created() {
        this.getTags();
        this.getGrid();
        this.getPlaceList();
    },
    mounted() {
        this.id = getRequest().id;
        this.getDetail();
    },
    methods: {
        // 获取场所
        getTags() {
            ajax({
                url: formal + '/place/tags',
                type: 'GET',
                success: (res) => {
                    this.tagList = res.data.list
                }
            })
        },
        // 地图上选择地址后确认按钮(确认选取的经纬度)
        confirmLocation() {
            this.isManual = false
            this.ruleForm.latitude = nowPoint[1]; // 纬度，浮点数，范围为90 ~ -90
            this.ruleForm.longitude = nowPoint[0]; // 经度，浮点数，范围为180 ~ -180。
            this.location = "经度:" + this.ruleForm.longitude + "   纬度:" + this.ruleForm.latitude
        },
        // 地图初始显示场所经纬度位置
        getLocation() {
            this.isManual = true
            setTimeout(() => {
                let currentData = gcj02ToWgs(this.tempObj.longitude, this.tempObj.latitude)
                this.getMap(currentData)
            }, 500)
        },
        // 判断当前坐标位置是否有图片，有就清除
        removeMarker() {
            if (marker1 != null) {
                map.removeOverLay(marker1);
                marker1 = null
            }
        },
        // 跳转到当前位置，并添加图标
        goCurrent() {
            if (this.time) {
                clearTimeout(this.time)
            }
            this.time = setTimeout(() => {
                this.removeMarker()
                wx.getLocation({
                    isHighAccuracy: true, // 结合gcj02提交定位精度
                    type: 'gcj02', // 默认为wgs84的 gps 坐标，如果要返回直接给 openLocation 用的火星坐标，可传入'gcj02'
                    complete: (res) => {
                        let currentData = gcj02ToWgs(res.longitude, res.latitude)
                        //创建图片对象
                        var icon = new T.Icon({
                            iconUrl: "./images/coordinates.png",
                            iconSize: new T.Point(25, 25),
                            // iconAnchor: new T.Point(10, 25)
                        });
                        marker1 = null
                        marker1 = new T.Marker(new T.LngLat(currentData[0], currentData[
                            1]), {
                            icon: icon
                        });
                        map.addOverLay(marker1);
                        map.centerAndZoom(new T.LngLat(currentData[0], currentData[1]),
                            18);
                    },
                });
            }, 500)
        },
        // 地图初始化
        getMap(res) {
            nowPoint = res
            //初始化地图对象
            if (map == null) {
                map = new T.Map("container");
            }
            //设置显示地图的中心点和级别
            map.centerAndZoom(new T.LngLat(res[0], res[1]), 18);
            map.setMinZoom(11);
            map.setMaxZoom(18);
            map.addEventListener("moveend", function (e) {
                nowPoint = [map.getCenter().getLng(), map.getCenter().getLat()]
            })
        },
        setCenter(location, bool) {
            this.map.setCenter([location.lng, location.lat])
        },
        //  新增备注里删除图片
        deleteNoteImage(index) {
            this.imagesList.splice(index, 1)
            this.noteImgNumber = 9 - this.imagesList.length
            this.isUploadNoteImg = true
        },
        // 上传图片  删除照片
        deleteImage(index) {
            this.ruleForm.images.splice(index, 1)
            this.imgNumber = 9 - this.ruleForm.images.length
            this.isUploadImg = true
        },
        // 删除联系人
        deleteBtn(index) {
            this.ruleForm.link_man_info.splice(index, 1)
        },
        // 新增备注弹窗
        addNoteBtn() {
            this.addNote = true
            // this.temp.images = []
            // this.temp.remark = ''
        },
        // 查看图片
        lookImg(list) {
            wx.previewImage({
                // current: 'http://admin.tangshan.youbo.me/upload/place/202211/7WBay02UiZx9mszwLJcjoEgrX5GYhPTV.jpg', // 当前显示图片的 http 链接
                urls: list // 需要预览的图片 http 链接列表
            });
        },
        // 点击完成时，删除照片
        deleteImg(id) {
            this.idList.map(item => {
                ajax({
                    url: formal + '/place/del-remark',
                    type: 'POST',
                    data: {
                        id: item,
                        place_id: this.id
                    },
                    success: (res) => {
                        this.prompt = true
                        this.msg = res.message
                        this.getDetail()
                    }
                })
            })
        },
        // 删除备注
        deleteImgBtn(id, index) {
            if (id != undefined) {
                this.idList.push(id)
            }
            this.ruleForm.remark_record.splice(index, 1)
        },
        // 新增备注点击完成方法
        noteOut() {
            var tempObj = {
                remark: this.newRrmark,
                images: this.imagesList,
                place_id: this.id
            }
            this.noteImgNumber = 9
            this.isUploadNoteImg = true
            this.temp = tempObj
            this.ruleForm.remark_record.push(tempObj)
            this.newRrmark = ""
            this.imagesList = []
            this.addNote = false
        },
        // 点击完成新增备注
        noteBtn() {
            this.ruleForm.remark_record.map(item => {
                if (item.id == undefined) {
                    ajax({
                        url: formal + '/place/add-remark',
                        type: 'POST',
                        data: item,
                        success: (res) => {
                            this.newRrmark = ""
                            this.imagesList = []
                        },
                        error: (res) => {
                            this.msg = res.message
                        }
                    })
                }
            })

        },
        // 要编辑的场所信息
        getDetail() {
            ajax({
                url: formal + '/place/place-info',
                type: 'GET',
                data: {
                    id: this.id
                },
                success: (res) => {
                    this.ruleForm = res.data
                    this.tempImages = res.data.images
                    this.tempObj = JSON.parse(JSON.stringify(this.ruleForm))
                    let newItem = {}
                    res.data.remark_record.map(item => {
                        newItem = item
                        newItem.str = item.create_time + ' ' + item.grids_person + ':' +
                            item.remark
                    })
                    this.location = "经度:" + res.data.longitude + "   纬度:" + res.data.latitude
                    for (var i = 0; i < this.communityInformation.length; i++) {
                        for (var x = 0; x < this.communityInformation[i].children.length; x++) {
                            if (res.data.grids_id == this.communityInformation[i].children[x].value) {
                                this.ruleForm.grids_id = [];
                                this.ruleForm.grids_id.push(this.communityInformation[i].value);
                                this.ruleForm.grids_id.push(this.communityInformation[i].children[x].value)
                            }
                        }
                    }
                }
            })
        },
        // 场所分类列表
        getPlaceList() {
            ajax({
                url: formal + '/place/category',
                type: 'GET',
                success: (res) => {
                    this.placeList = res.data.list
                    res.data.list.map(item => {
                        if (item.cate_id == this.ruleForm.category_id) {
                            for (var i in this.additionalObj) {
                                if (i == this.ruleForm.category_id) {
                                    this.additionalList = this.additionalObj[this.ruleForm.category_id]
                                }
                            }
                            this.ruleForm.category_id = item.cate_name
                        }
                    })
                    this.$forceUpdate()
                }
            })
        },
        // 关闭弹窗
        goPlaceMan() {
            if (this.msg == '修改成功' || this.msg == '备注删除成功') {
                this.prompt = false
                window.location.href = 'placeManagement.html'
            } else {
                this.prompt = false
            }
        },
        // 选择场所change事件
        getValue(id) {
            for (var i in this.additionalObj) {
                if (id == this.ruleForm.category_id) {
                    this.additionalList = this.additionalObj[this.ruleForm.category_id]
                }
            }
        },
        // 附加字段
        getAdditional() {
            ajax({
                url: formal + '/place/get-place-fields',
                type: 'GET',
                success: (res) => {
                    this.additionalObj = res.data
                    this.getPlaceList()
                }
            })
        },
        // 确认修改场所信息
        placeEditor(formName) {
            console.log(this.ruleForm);
            if (nowPoint != null) {
                let gaodeList = wgs84Togcj02(nowPoint[0], nowPoint[1])
                this.ruleForm.longitude = gaodeList[0]
                this.ruleForm.latitude = gaodeList[1]
            }
            this.loading = true
            if (this.ruleForm.place_name == "") {
                this.prompt = true
                this.loading = false
                this.msg = '请输入场所名称'
                return
            } else if (this.ruleForm.category_id == "") {
                this.prompt = true
                this.loading = false
                this.msg = '请选择场所分类'
                return
            } else if (this.ruleForm.is_small_place === "") {
                this.prompt = true
                this.loading = false
                this.msg = '请选择是否为九小场所'
                return
            } else if (this.ruleForm.is_cater === "") {
                this.prompt = true
                this.loading = false
                this.msg = '请选择是否涉餐饮'
                return
            } else if (this.ruleForm.link_man_info.length == 0) {
                this.prompt = true
                this.loading = false
                this.msg = '请填写联系人信息'
                return
            } else
            if (this.ruleForm.grids_id.length == 0) {
                this.prompt = true
                this.loading = false
                this.msg = '请选择网格'
                return
            } else if (this.ruleForm.link_man_info.length == 0) {
                this.prompt = true
                this.loading = false
                this.msg = '请填写基本情况说明'
                return
            } else if (this.ruleForm.address == "") {
                this.prompt = true
                this.loading = false
                this.msg = '请输入场所信息'
                return
            } else if (this.ruleForm.first_tags == "") {
                this.prompt = true
                this.loading = false
                this.msg = '请输入场所主标签'
                return
            } else {
                this.ruleForm.link_man_info.map(item => {
                    if (item.name == "") {
                        this.prompt = true
                        this.loading = false
                        this.msg = '请输入联系人姓名'
                        return
                    }
                    if (item.phone == "") {
                        this.prompt = true
                        this.loading = false
                        this.msg = '请输入联系人手机号'
                        return
                    }
                    if (!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(item.phone)) {
                        this.prompt = true
                        this.loading = false
                        this.msg = '请输入正确的手机格式'
                        return
                    }
                })
            }
            for (var i = 0; i < this.additionalList.length; i++) {
                let fieldName = this.ruleForm[this.additionalList[i].field_name]
                if (fieldName === "") {
                    this.msg = this.additionalList[i].hint
                    this.prompt = true
                    this.loading = false
                    return
                } else if (fieldName === undefined) {
                    this.msg = this.additionalList[i].hint
                    this.prompt = true
                    this.loading = false
                    return
                }
            }

            if (Array.isArray(this.ruleForm.grids_id)) {
                var x = this.ruleForm.grids_id.pop();
                this.ruleForm.grids_id = x;
            }

            this.placeList.map(item => {
                if (item.cate_name == this.ruleForm.category_id) {
                    this.ruleForm.category_id = item.cate_id
                }
            })
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    ajax({
                        url: formal + '/place/save-place',
                        type: "POST",
                        data: this.ruleForm,
                        success: (res) => {
                            this.noteBtn()
                            this.deleteImg()
                            this.prompt = true
                            this.loading = false
                            this.msg = res.message
                        },
                        error: (res) => {
                            this.prompt = true
                            this.msg = res.responseJSON.message
                            this.loading = false
                        }
                    })
                } else {
                    this.prompt = true
                    this.msg = res.message
                    this.loading = false
                }
            });

        },
        // 新增联系人
        addPrincipal() {
            let obj = {
                name: '',
                phone: ''
            }
            this.ruleForm.link_man_info.push(obj)
        },
        // 上传图片判断上传长度，判断图片上传or备注图片上传
        uploadImageBtn(type) {
            let imgNum = null
            if (type == 1) {
                this.imgNumber = 9 - this.ruleForm.images.length
                if (this.imgNumber == 0) {
                    this.isUploadImg = false
                }
                imgNum = this.imgNumber
            } else if (type == 2) {
                this.noteImgNumber = 9 - this.imagesList.length
                if (this.noteImgNumber == 0) {
                    this.isUploadNoteImg = false
                }
                imgNum = this.noteImgNumber
            }
            wx.ready(() => {
                wx.chooseImage({
                    count: imgNum, // 默认9
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                    success: (res) => {
                        var localIds = res
                            .localIds; // 返回选定照片的本地 ID 列表，localId可以作为 img 标签的 src 属性显示图片
                        this.uploadImg(localIds, type);
                    }
                })
            })
        },
        // 多图上传，判断上传长度执行回调
        uploadImg(localIds, type) {
            this.isUploadLoading = true
            var localId = localIds.shift();
            wx.uploadImage({
                localId: localId, // 需要上传的图片的本地ID，由 chooseImage 接口获得
                isShowProgressTips: 0, // 默认为1，显示进度提示
                success: (res) => {
                    var serverId = res.serverId; // 返回图片的服务器端ID
                    this.downloadImg(serverId, type)
                    if (localIds.length > 0) {
                        this.uploadImg(localIds, type)
                    }
                }
            })
        },
        // 上传成功后调取接口，获取图片地址做展示
        downloadImg(serverId, type) {
            ajax({
                url: formal + '/files/get-wx-media',
                type: 'POST',
                async: false,
                data: {
                    mediaId: serverId
                },
                success: (res) => {
                    if (res.status == 1) {
                        if (type == 1 && this.ruleForm.images.length <= 8) {
                            this.ruleForm.images.push(res.data.url)
                            this.imgNumber = 9 - this.ruleForm.images.length
                            if (this.imgNumber == 0) {
                                this.isUploadImg = false
                            }
                            this.isUploadLoading = false
                        } else if (type == 2 && this.imagesList.length <= 8) {
                            this.imagesList.push(res.data.url)
                            this.noteImgNumber = 9 - this.imagesList.length
                            if (this.noteImgNumber == 0) {
                                this.isUploadNoteImg = false
                            }
                            this.isUploadLoading = false
                        }
                    }
                }
            })
        },
        handleChange(value) {
            console.log(value)
            // this.ruleForm.grids_id = '';
            // this.ruleForm.grids_id = value.pop();
            this.ruleForm.grids_id = value;
        },
        // 获取网格
        getGrid() {
            ajax({
                url: formal + '/place/get-grids-fields',
                type: 'GET',
                success: (res) => {
                    this.communityInformation = res.data;
                }
            })
        }
        // 上传转换base64
        // uploadImageBtn(type) {
        // 	console.log(getToken)
        // 	wx.chooseImage({
        // 		count: 1, // 默认9
        // 		sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        // 		sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        // 		success: (res) => {
        // 			var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
        // 			console.log("图片id", localIds[0]);

        // 			wx.getLocalImgData({
        // 				localId: localIds[0],
        // 				success: (res) => {
        // 					var localData = res.localData;
        // 					var u = navigator.userAgent;
        // 					var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
        // 					if (isiOS) {
        // 						//是ios直接使用
        // 						localData = localData.replace('data:image/jgp',
        // 							'data:image/jpeg')
        // 						// getimgurlbydata(localData);
        // 					} else {
        // 						localData = localData.replace(/\r|\n/g, '').replace(
        // 							'data:image/jgp', 'data:image/jpeg')
        // 						//第一个替换的是换行符，第二个替换的是图片类型，因为在IOS机上测试时看到它的图片类型时jgp，
        // 						localData = "data:image/jpg;base64," + localData;
        // 						console.log(localData)
        // 						console.log("图片", localData.substring(0, 30));
        // 						// getimgurlbydata(localData);
        // 					}
        // 					if (type == 1 && this.ruleForm.images.length <= 8) {
        // 						$.ajax({
        // 							url: formal + '/files/image',
        // 							type: 'POST',
        // 							headers: {
        // 								Authorization: 'Bearer ' + getToken
        // 							},
        // 							data: {
        // 								image: localData
        // 							},
        // 							success: (res) => {
        // 								console.log(res)
        // 								this.ruleForm.images.push(res
        // 									.data.url)
        // 							}
        // 						})
        // 					} else if (type == 2 && this.imagesList.length <= 8) {
        // 						$.ajax({
        // 							url: formal + '/files/image',
        // 							type: 'POST',
        // 							headers: {
        // 								Authorization: 'Bearer ' + getToken
        // 							},
        // 							data: {
        // 								image: localData
        // 							},
        // 							success: (res) => {
        // 								this.imagesList.push(res.data
        // 									.url)
        // 							}
        // 						})
        // 					} else {
        // 						this.prompt = true
        // 						this.msg = "图片最多上传9张"
        // 						return
        // 					}
        // 				},
        // 				fail: function(res) {
        // 					console.log("进入失败", res)
        // 				}
        // 			});
        // 		},
        // 		fail: function(res) {
        // 			console.log("开启失败", res)
        // 		}
        // 	});
        // }
    }
})